/**
 * Created by lixiaodi on 2019/06/28 0027.
 */
//得到新增类型
var passData = JSON.parse(localStorage.getItem("newNotice"));
console.log(passData)
//得到登录人信息
var userInfo = JSON.parse(localStorage.getItem("item"));

mini.parse();

var form = new mini.Form("form1");  			//得到页面上的表单
var articleType = mini.get('articleType');		//类型
var sender = mini.getByName('publisher');		//发布人
var nowTime = mini.getByName('publisher_date');	//发布时间
var creatTime = mini.getByName('creat_date');	//创建时间
var depEl = mini.getByName('depids');			//发布范围
//var ue = UE.getEditor('content');				//富文本编辑器

var timestamp = Date.parse(new Date());			//获取当前时间
timestamp = formatDateSec(timestamp);			//时间格式转换
var articleData = '';
var userId = '';
var userName = '';
//得到编辑器并取消自增高度
var ue = UE.getEditor('content', {
    //设置不自动增加高度
    scaleEnabled: true
});
//页面初始化	
$(function () {
    //管理页面新增跳转
    if (passData) {
        console.log(passData.types)
        if (passData.types == 'new') {
            //赋值
            articleType.setValue(passData.pageTitle);
            console.log(userInfo)
            userName = userInfo.uName;
            userId = userInfo.userId;
            console.log(userName)
            sender.setValue(userName);
            creatTime.setValue(timestamp);
        } else if (passData.types == 'edit') {
            articleData = passData.articleData;
            //根据id查询
            $.ajax({
                url: ajaxUrl + '/findById.do?id=' + passData.articleData.notice_id,
                type: 'POST',
                success: function (data) {
                    if (data.status == 200) {
                        console.log(data,'返回值')
                        //周例会信息
                        articleData = data.data;
                        //发布范围信息
                        var releaseScope = data.deps;
                        //类型赋值
                        if (articleData.notice_type == '1') {
                            articleData.notice_type = '公告';
                        } else if (articleData.notice_type == '2') {
                            articleData.notice_type = '周例会';
                        } else if (articleData.notice_type == '3') {
                            articleData.notice_type = '新闻';
                        }
                        //发布人id赋值
                        userId = articleData.publisher;
                        //发布人姓名赋值
                        articleData.publisher = data.publisher.uName;
                        //赋值
                        form.setData(articleData);
                        //发布范围赋值
                        if (releaseScope.length > 0) {
                            var ids = [];
                            var names = [];
                            for (var i = 0, l = releaseScope.length; i < l; i++) {
                                var r = releaseScope[i];
                                ids.push(r.DepartmentalManagement_id);
                                names.push(r.DepartmentalManagement_name);
                            }
                            var id = ids.join(',');
                            var nameText = names.join(',');
                            depEl.setValue(id);
                            depEl.setText(nameText);
                        }
                        //富文本赋值
                        var ueContent = articleData.notice_content;
                        //消息详情赋值
                        //ue.setContent(ueContent);
                        ue.addListener('ready',function(){
                            //消息详情赋值
                            ue.setContent(ueContent);
                        });
                        /*ue.addListener('ready',function(){

                        });*/
                    }
                },
                error: function (data) {
                    console.log('请求失败');
                }
            })

        }
        //发布时间赋值
        //nowTime.setValue(timestamp);
    } else {
        //获取当前选项卡
        var tab = parent.tabsEl.getActiveTab();

        var notTypes = '';
        //判断是按钮打开还是菜单打开
        if (tab.name.substr(0, 4) == 'menu') {
            if (tab.title == '新增例会') {
                notTypes = '周例会';
            } else if (tab.title === '新增公告01') {
                notTypes = '公告';
            } else if (tab.title == '新增新闻') {
                notTypes = '新闻';
            }
            //赋值
            articleType.setValue(notTypes);
            userName = userInfo.uName;
            userId = userInfo.userId;
            sender.setValue(userName);
            creatTime.setValue(timestamp);
        } else {
            console.log('传值失败');
        }
    }
})

//选择部门
function onChange() {
    mini.open({
        url: bootPATH + "../frame/frame1/pages/booking/noticeManagement/changeDep.html",
        title: "部门列表",
        width: 700,
        height: 500,
        showCloseButton:false,
        onload: function () {
            var iframe = this.getIFrameEl();
            var addData = depEl.getValue();
            var data = {addData: addData};
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {
            if (action == "close") return false;
            if (action == "save") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.GetData();
                data = mini.clone(data);               //必须
                console.log(data)
                if (data.length > 0) {
                    var ids = [];
                    var names = [];
                    for (var i = 0; i < data.length; i++) {
                        var r = data[i];
                        ids.push(r.id);
                        names.push(r.name);
                    }
                    var id = ids.join(',');
                    var nameText = names.join(',');
                    depEl.setValue(id);
                    depEl.setText(nameText);
                } else {
                    mini.alert("请选中一条记录");
                }
            }

        }
    });
}

//保存
function onSave() {
    var timestampSend = Date.parse(new Date());			//获取当前时间
    timestampSend = formatDateSec(timestampSend);			//时间格式转换
    //校验
    form.validate();
    if (form.isValid() == false) return;
    //得到要保存的值
    var formData = form.getData();
    console.log(formData, '所有值');
    //编辑器中的值
    //var content = ue.getPlainTxt();
    var content = ue.getContent();
    console.log(content,'富文本框')
    //类型
    switch (formData.notice_type) {
        case '公告':
            formData.notice_type = 1;
            break;
        case '新闻':
            formData.notice_type = 2;
            break;
        case '周例会':
            formData.notice_type = 3;
            break;
    }
    var msgObj = {
        notice_id: formData.notice_id,
        notice_name: formData.notice_name,
        publisher: userId,
        depids: formData.depids,
        notice_type: formData.notice_type,
        user_id: formData.user_id,
        creat_date: formData.creat_date,
        publisher_date: timestampSend,
        notice_content: content,
        publisher_state: 0
    };
    var paramStr = JSON.stringify(msgObj);
    $.ajax({
        url: ajaxUrl + "/saveWeeklyNotice.do",
        type: 'POST',
        data: paramStr,
        contentType: "application/json",
        success: function (data) {
            if (data.status == 200) {
                showTip(data.message);
                mini.alert('发布成功,点击确定关闭页面', '系统提示', function (action) {
                    if (action == 'ok') {
                        //获取当前选项卡
                        var tabClose = parent.tabsEl.getActiveTab();
                        //关闭当前选项卡
                        parent.articleTab(tabClose);
                    }
                });
            } else {
                mini.alert(data.status);
            }
            // showTip(data.message);
        },
        error: function (data) {
            console.log(data);
        }
    })
}

//保存并发布
function onsaveAndPub() {
    var timestampSend = Date.parse(new Date());			//获取当前时间
    timestampSend = formatDateSec(timestampSend);			//时间格式转换
    //校验
    form.validate();
    if (form.isValid() == false) return;
    //得到要保存的值
    var formData = form.getData();
    //编辑器中的值
    //var content = ue.getPlainTxt();
    var content = ue.getContent();
    //类型
    switch (formData.notice_type) {
        case '公告':
            formData.notice_type = 1;
            break;
        case '新闻':
            formData.notice_type = 2;
            break;
        case '周例会':
            formData.notice_type = 3;
            break;
    }
    var msgObj = {
        notice_id: formData.notice_id,
        notice_name: formData.notice_name,
        publisher: userId,
        depids: formData.depids,
        notice_type: formData.notice_type,
        user_id: formData.user_id,
        creat_date: formData.creat_date,
        publisher_date: timestampSend,
        notice_content: content,
        publisher_state: 0
    };
    var paramStr = JSON.stringify(msgObj);
    $.ajax({
        url: ajaxUrl + "/saveNotice.do",
        type: 'POST',
        data: paramStr,
        contentType: "application/json",
        success: function (data) {
            if (data.status == 200) {
                var noticeId = '';
                //判断是新增还是编辑
                if (formData.notice_id) {
                    noticeId = formData.notice_id;
                } else {
                    noticeId = data.data.notice_id;
                }
                console.log(data)
                //发布
                $.ajax({
                    url: ajaxUrl + '/publishNotice.do?state=1&param=' + noticeId,
                    type: "post",
                    success: function (data) {
                        if (data.status == 200) {
                            showTip(data.message);
                            mini.alert('发布成功,点击确定关闭页面', '系统提示', function (action) {
                                if (action == 'ok') {
                                    //获取当前选项卡
                                    var tabClose = parent.tabsEl.getActiveTab();
                                    //关闭当前选项卡
                                    parent.articleTab(tabClose);
                                }
                            });
                        } else {
                            mini.alert(data.status);
                        }
                    },
                    error: function () {
                        mini.alert('失败');
                    }
                });
            } else {
                mini.alert(data.status);
            }

        },
        error: function (data) {
            console.log(data);
        }
    })
}

//取消
function onCancel() {
    //清空填写内容
    //赋值
    // articleType.setValue(passData.pageTitle);
    // userName = userInfo.uName;
    // userId = userInfo.userId;
    // sender.setValue(userName);
    // creatTime.setValue(timestamp);
    // ue.setContent('');
    //获取当前选项卡
    var tabClose = parent.tabsEl.getActiveTab();
    //关闭当前选项卡
    parent.articleTab(tabClose);
}

//校验模块必输
function onNotSpaceValidation(e) {
    if (e.isValid) {
        if (!e.value) {
            e.errorText = "不能为空";
            e.isValid = false;
        }
    }
}

//提示信息
function showTip(text) {
    mini.showTips({
        content: "<b>" + text + "</b>",
        state: "success",
        x: "center",
        y: "center",
        timeout: 2000
    });
}
